import 'dart:convert';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/demo/data/repository/demo_repository_impl.dart';
import 'package:casdon/modules/demo/ui/screen/demo_sse_utitls.dart';
import 'package:casdon/modules/me/data/repository/me_repository_impl.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_markdown/flutter_markdown.dart'; // 导入 markdown 渲染库

class DemoSseScreen extends ConsumerStatefulWidget {
  final String imageUrl;

  const DemoSseScreen({super.key, required this.imageUrl});

  @override
  _DemoSseScreenState createState() => _DemoSseScreenState();
}

class _DemoSseScreenState extends ConsumerState<DemoSseScreen> {
  bool _connected = false;
  StringBuffer _messageBuffer = StringBuffer(); // 用来拼接接收到的消息内容

  @override
  void initState() {
    super.initState();
    _sseStream(widget.imageUrl);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('AI 推荐')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const SizedBox(height: 20),

            if (_connected) ...[const SizedBox(height: 20)],
            const SizedBox(height: 20),
            Expanded(
              child: SingleChildScrollView(
                child: MarkdownBody(
                  data: _messageBuffer.toString(), // 展示拼接后的 Markdown 内容
                ),
              ),
            ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  // 处理拍照点击事件
  _sseStream(String imgUrl) async {
    startSSE(
      onDone: () => _onDone(),
      onError: (e) => _onError(e),
      onMessage: (data) => _onMessage(data),
      onConnectSuccess: () => _onConnectSuccess(ref, imgUrl),
    );
  }

  _onDone() {
    // 连接关闭后的处理
    setState(() {
      _connected = false;
    });
  }

  _onError(Exception e) {
    // 错误处理
    // Log.e("SSE Error = $e");
  }

  _onMessage(String data) {
    RegExp regExp = RegExp(r'(?<=data:)\{.*?\}');
    Match? match = regExp.firstMatch(data);
    Log.i("SSE Message = $data");

    if (match != null) {
      // 提取到的 JSON 字符串
      String jsonString = match.group(0)!;

      // 解析 JSON 字符串
      Map<String, dynamic> jsonData = jsonDecode(jsonString);

      // 提取 text 字段的内容
      String text = jsonData['text'];

      // 打印提取的 text 内容
      Log.i("SSE Message = $text");

      // 使用 StringBuffer 拼接新的内容
      setState(() {
        _messageBuffer.write(text); // 拼接新的消息内容
        // _messageBuffer.write("\n\n"); // 可加换行符分隔消息段
      });
    }
  }

  _onConnectSuccess(WidgetRef ref, String url) {
    // 连接成功时的处理，只执行一次
    if (!_connected) {
      setState(() {
        _connected = true;
        _messageBuffer.clear();
        _messageBuffer = StringBuffer();
      });
    }
    ref.read(demoRepositoryProvider).recipeStreamCall(url, "");
  }
}
